package com.huika.lib.encrypt;

import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateCrtKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Map;

import javax.crypto.Cipher;

import com.huika.lib.encrypt.encoder.BASE64Decoder;
import com.huika.lib.encrypt.encoder.BASE64Encoder;

public class RsaHelper {
	/** */
	/**
	 * RSA最大加密明文大小
	 */
	private static final int MAX_ENCRYPT_BLOCK = 117;

	/** */
	/**
	 * RSA最大解密密文大小
	 */
	private static final int MAX_DECRYPT_BLOCK = 128;

	/**
	 * 生成RSA密钥对(默认密钥长度为1024)
	 * 
	 * @return
	 */
	public static KeyPair generateRSAKeyPair() {
		return generateRSAKeyPair(1024);
	}

	/**
	 * 生成RSA密钥对
	 * 
	 * @param keyLength
	 *            密钥长度，范围：512～2048
	 * @return
	 */
	public static KeyPair generateRSAKeyPair(int keyLength) {
		try {
			// KeyPairGenerator kpg =
			// KeyPairGenerator.getInstance("RSA/ECB/PKCS1Padding");
			KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
			kpg.initialize(keyLength);
			return kpg.genKeyPair();
		} catch (NoSuchAlgorithmException e) {
			return null;
		}
	}

	public static String encode64PublicKeyString(PublicKey key) throws Exception {
		// RSAPublicKey rsaPublickey = (RSAPublicKey)key;
		byte[] keyBytes = key.getEncoded();
		String s = (new BASE64Encoder()).encode(keyBytes);
		return s;
	}

	public static String encode64PrivateKeyString(PrivateKey key) throws Exception {
		// RSAPrivateKey rsaPrivateKey = (RSAPrivateKey)key;
		byte[] keyBytes = key.getEncoded();
		String s = (new BASE64Encoder()).encode(keyBytes);
		return s;
	}

	/**
	 * 得到公钥
	 * 
	 * @param key
	 *            密钥字符串（经过base64编码）
	 * @throws Exception
	 */
	public static PublicKey decodePublicKeyFromBase64Str(String key) throws Exception {
		byte[] keyBytes;
		keyBytes = (new BASE64Decoder()).decodeBuffer(key);
		X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		PublicKey publicKey = keyFactory.generatePublic(keySpec);
		return publicKey;
	}

	/**
	 * 得到私钥
	 * 
	 * @param key
	 *            密钥字符串（经过base64编码）
	 * @throws Exception
	 */
	public static PrivateKey decodePrivateKeyFromBase64Str(String key) throws Exception {
		byte[] keyBytes;
		keyBytes = (new BASE64Decoder()).decodeBuffer(key);
		PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
		return privateKey;
	}

	/**
	 * java端公钥转换成C#公钥
	 */
	public static String encodePublicKeyToXml(PublicKey key) {
		if (!RSAPublicKey.class.isInstance(key)) {
			return null;
		}
		RSAPublicKey pubKey = (RSAPublicKey) key;
		StringBuilder sb = new StringBuilder();

		sb.append("<RSAKeyValue>");
		sb.append("<Modulus>").append(Base64Helper.encode(pubKey.getModulus().toByteArray())).append("</Modulus>");
		sb.append("<Exponent>").append(Base64Helper.encode(pubKey.getPublicExponent().toByteArray())).append("</Exponent>");
		sb.append("</RSAKeyValue>");
		return sb.toString();
	}

	/*
	 * C#端公钥转换成java公钥
	 */
	public static PublicKey decodePublicKeyFromXml(String xml) {
		xml = xml.replaceAll("\r", "").replaceAll("\n", "");
		BigInteger modulus = new BigInteger(1, Base64Helper.decode(RsaStringUtils.getMiddleString(xml, "<Modulus>", "</Modulus>")));
		BigInteger publicExponent = new BigInteger(1, Base64Helper.decode(RsaStringUtils.getMiddleString(xml, "<Exponent>", "</Exponent>")));
		RSAPublicKeySpec rsaPubKey = new RSAPublicKeySpec(modulus, publicExponent);
		KeyFactory keyf;
		try {
			keyf = KeyFactory.getInstance("RSA");
			return keyf.generatePublic(rsaPubKey);
		} catch (Exception e) {
			return null;
		}
	}

	/*
	 * C#端私钥转换成java私钥
	 */
	public static PrivateKey decodePrivateKeyFromXml(String xml) {
		xml = xml.replaceAll("\r", "").replaceAll("\n", "");
		BigInteger modulus = new BigInteger(1, Base64Helper.decode(RsaStringUtils.getMiddleString(xml, "<Modulus>", "</Modulus>")));
		BigInteger publicExponent = new BigInteger(1, Base64Helper.decode(RsaStringUtils.getMiddleString(xml, "<Exponent>", "</Exponent>")));
		BigInteger privateExponent = new BigInteger(1, Base64Helper.decode(RsaStringUtils.getMiddleString(xml, "<D>", "</D>")));
		BigInteger primeP = new BigInteger(1, Base64Helper.decode(RsaStringUtils.getMiddleString(xml, "<P>", "</P>")));
		BigInteger primeQ = new BigInteger(1, Base64Helper.decode(RsaStringUtils.getMiddleString(xml, "<Q>", "</Q>")));
		BigInteger primeExponentP = new BigInteger(1, Base64Helper.decode(RsaStringUtils.getMiddleString(xml, "<DP>", "</DP>")));
		BigInteger primeExponentQ = new BigInteger(1, Base64Helper.decode(RsaStringUtils.getMiddleString(xml, "<DQ>", "</DQ>")));
		BigInteger crtCoefficient = new BigInteger(1, Base64Helper.decode(RsaStringUtils.getMiddleString(xml, "<InverseQ>", "</InverseQ>")));

		RSAPrivateCrtKeySpec rsaPriKey = new RSAPrivateCrtKeySpec(modulus, publicExponent, privateExponent, primeP, primeQ, primeExponentP, primeExponentQ, crtCoefficient);
		KeyFactory keyf;
		try {
			keyf = KeyFactory.getInstance("RSA");
			return keyf.generatePrivate(rsaPriKey);
		} catch (Exception e) {
			return null;
		}
	}

	/*
	 * java端私钥转换成C#私钥
	 */
	public static String encodePrivateKeyToXml(PrivateKey key) {
		if (!RSAPrivateCrtKey.class.isInstance(key)) {
			return null;
		}
		RSAPrivateCrtKey priKey = (RSAPrivateCrtKey) key;
		StringBuilder sb = new StringBuilder();

		sb.append("<RSAKeyValue>");
		sb.append("<Modulus>").append(Base64Helper.encode(priKey.getModulus().toByteArray())).append("</Modulus>");
		sb.append("<Exponent>").append(Base64Helper.encode(priKey.getPublicExponent().toByteArray())).append("</Exponent>");
		sb.append("<P>").append(Base64Helper.encode(priKey.getPrimeP().toByteArray())).append("</P>");
		sb.append("<Q>").append(Base64Helper.encode(priKey.getPrimeQ().toByteArray())).append("</Q>");
		sb.append("<DP>").append(Base64Helper.encode(priKey.getPrimeExponentP().toByteArray())).append("</DP>");
		sb.append("<DQ>").append(Base64Helper.encode(priKey.getPrimeExponentQ().toByteArray())).append("</DQ>");
		sb.append("<InverseQ>").append(Base64Helper.encode(priKey.getCrtCoefficient().toByteArray())).append("</InverseQ>");
		sb.append("<D>").append(Base64Helper.encode(priKey.getPrivateExponent().toByteArray())).append("</D>");
		sb.append("</RSAKeyValue>");
		return sb.toString();
	}

	// 用公钥加密
	public static byte[] encryptData(byte[] data, PublicKey pubKey) {
		try {
			/*
			 * Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
			 * cipher.init(Cipher.ENCRYPT_MODE, pubKey); return
			 * cipher.doFinal(data);
			 */
			Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
			cipher.init(Cipher.ENCRYPT_MODE, pubKey);

			int inputLen = data.length;
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			int offSet = 0;
			byte[] cache;
			int i = 0;
			// 对数据分段解密
			while (inputLen - offSet > 0) {
				if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
					cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
				} else {
					cache = cipher.doFinal(data, offSet, inputLen - offSet);
				}
				// 写入内存缓冲区
				out.write(cache, 0, cache.length);
				i++;
				offSet = i * MAX_ENCRYPT_BLOCK;
			}
			// 获取内存缓冲中的数据，转换成数组
			byte[] decryptedData = out.toByteArray();
			out.close();
			return decryptedData;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	// 用私钥解密
	public static byte[] decryptData(byte[] encryptedData, PrivateKey priKey) {
		try {
			/*
			 * Cipher cipher = Cipher.getInstance("RSA");
			 * cipher.init(Cipher.DECRYPT_MODE, priKey); return
			 * cipher.doFinal(encryptedData);
			 */
			Cipher cipher = Cipher.getInstance("RSA");
			cipher.init(Cipher.DECRYPT_MODE, priKey);
			int inputLen = encryptedData.length;
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			int offSet = 0;
			byte[] cache;
			int i = 0;
			// 对数据分段解密
			while (inputLen - offSet > 0) {
				if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
					cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
				} else {
					cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
				}
				// 写入内存缓冲区
				out.write(cache, 0, cache.length);
				i++;
				offSet = i * MAX_DECRYPT_BLOCK;
			}
			// 获取内存缓冲中的数据，转换成数组
			byte[] decryptedData = out.toByteArray();
			out.close();
			return decryptedData;
		} catch (Exception e) {
			return null;
		}
	}

	// 用私钥加密
	public static byte[] encryptData(byte[] data, PrivateKey priKey) {
		try {
			/*
			 * Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
			 * cipher.init(Cipher.ENCRYPT_MODE, pubKey); return
			 * cipher.doFinal(data);
			 */
			Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
			cipher.init(Cipher.ENCRYPT_MODE, priKey);

			int inputLen = data.length;
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			int offSet = 0;
			byte[] cache;
			int i = 0;
			// 对数据分段解密
			while (inputLen - offSet > 0) {
				if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
					cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
				} else {
					cache = cipher.doFinal(data, offSet, inputLen - offSet);
				}
				// 写入内存缓冲区
				out.write(cache, 0, cache.length);
				i++;
				offSet = i * MAX_ENCRYPT_BLOCK;
			}
			// 获取内存缓冲中的数据，转换成数组
			byte[] decryptedData = out.toByteArray();
			out.close();
			return decryptedData;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	// 用公钥解密
	public static byte[] decryptData(byte[] encryptedData, PublicKey pubKey) {
		try {
			/*
			 * Cipher cipher = Cipher.getInstance("RSA");
			 * cipher.init(Cipher.DECRYPT_MODE, priKey); return
			 * cipher.doFinal(encryptedData);
			 */
			// 安卓使用的界面方法
			Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
			// JAVA使用的解密方法
			// Cipher cipher = Cipher.getInstance("RSA");
			cipher.init(Cipher.DECRYPT_MODE, pubKey);
			int inputLen = encryptedData.length;
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			int offSet = 0;
			byte[] cache;
			int i = 0;
			// 对数据分段解密
			while (inputLen - offSet > 0) {
				if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
					cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
				} else {
					cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
				}
				// 写入内存缓冲区
				out.write(cache, 0, cache.length);
				i++;
				offSet = i * MAX_DECRYPT_BLOCK;
			}
			// 获取内存缓冲中的数据，转换成数组
			byte[] decryptedData = out.toByteArray();
			out.close();
			return decryptedData;
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 根据指定公钥进行明文加密
	 * 
	 * @param plainText
	 *            要加密的明文数据
	 * @param pubKey
	 *            公钥
	 * @return
	 */
	public static String encryptDataFromStr(String plainText, PublicKey pubKey) {

		try {
			byte[] dataByteArray = plainText.getBytes("gb2312");
			byte[] encryptedDataByteArray = RsaHelper.encryptData(dataByteArray, pubKey);
			return Base64Helper.encode(encryptedDataByteArray);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}
	}

	/**
	 * 根据指定私钥对数据进行签名(默认签名算法为"SHA1withRSA")
	 * 
	 * @param data
	 *            要签名的数据
	 * @param priKey
	 *            私钥
	 * @return
	 */
	public static byte[] signData(byte[] data, PrivateKey priKey) {
		return signData(data, priKey, "SHA1withRSA");
	}

	/**
	 * 根据指定私钥和算法对数据进行签名
	 * 
	 * @param data
	 *            要签名的数据
	 * @param priKey
	 *            私钥
	 * @param algorithm
	 *            签名算法
	 * @return
	 */
	public static byte[] signData(byte[] data, PrivateKey priKey, String algorithm) {
		try {
			Signature signature = Signature.getInstance(algorithm);
			signature.initSign(priKey);
			signature.update(data);
			return signature.sign();
		} catch (Exception ex) {
			return null;
		}
	}

	/**
	 * 用指定的公钥进行签名验证(默认签名算法为"SHA1withRSA")
	 * 
	 * @param data
	 *            数据
	 * @param sign
	 *            签名结果
	 * @param pubKey
	 *            公钥
	 * @return
	 */
	public static boolean verifySign(byte[] data, byte[] sign, PublicKey pubKey) {
		return verifySign(data, sign, pubKey, "SHA1withRSA");
	}

	/**
	 * 
	 * @param data
	 *            数据
	 * @param sign
	 *            签名结果
	 * @param pubKey
	 *            公钥
	 * @param algorithm
	 *            签名算法
	 * @return
	 */
	public static boolean verifySign(byte[] data, byte[] sign, PublicKey pubKey, String algorithm) {
		try {
			Signature signature = Signature.getInstance(algorithm);
			signature.initVerify(pubKey);
			signature.update(data);
			return signature.verify(sign);
		} catch (Exception ex) {
			return false;
		}
	}

	/**
	 * 从字符串中加载公钥
	 * 
	 * @param publicKeyStr
	 *            公钥数据字符串
	 * @throws Exception
	 *             加载公钥时产生的异常
	 */
	public static RSAPublicKey loadPublicKeyByStr(String publicKeyStr) throws Exception {
		try {
			byte[] buffer = Base64.decode(publicKeyStr);
			KeyFactory keyFactory = KeyFactory.getInstance("RSA");
			X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
			return (RSAPublicKey) keyFactory.generatePublic(keySpec);
		} catch (NoSuchAlgorithmException e) {
			throw new Exception("无此算法");
		} catch (InvalidKeySpecException e) {
			throw new Exception("公钥非法");
		} catch (NullPointerException e) {
			throw new Exception("公钥数据为空");
		}
	}

	/**
	 * 从字符串加密私钥
	 * 
	 * @param privateKeyStr
	 * @return
	 * @throws Exception
	 * @see [类、类#方法、类#成员]
	 */
	public static RSAPrivateKey loadPrivateKeyByStr(String privateKeyStr) throws Exception {
		try {
			byte[] buffer = Base64.decode(privateKeyStr);
			PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
			KeyFactory keyFactory = KeyFactory.getInstance("RSA");
			return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
		} catch (NoSuchAlgorithmException e) {
			throw new Exception("无此算法");
		} catch (InvalidKeySpecException e) {
			throw new Exception("私钥非法");
		} catch (NullPointerException e) {
			throw new Exception("私钥数据为空");
		}
	}

	public static void main(String[] args) {
		KeyPair kp = RsaHelper.generateRSAKeyPair();
		PublicKey pubKey = kp.getPublic();
		PrivateKey priKey = kp.getPrivate();

		/*
		 * String pubKeyXml = RsaHelper.encodePublicKeyToXml(pubKey); String
		 * priKeyXml = RsaHelper.encodePrivateKeyToXml(priKey);
		 * System.out.println("====公钥===="); System.out.println(pubKeyXml);
		 * System.out.println("====私钥===="); System.out.println(priKeyXml);
		 * 
		 * PublicKey pubKey2 = RsaHelper.decodePublicKeyFromXml(pubKeyXml);
		 * PrivateKey priKey2 = RsaHelper.decodePrivateKeyFromXml(priKeyXml);
		 * 
		 * System.out.println("====公钥对比====");
		 * System.out.println(pubKey.toString()); System.out.println("------");
		 * System.out.println(pubKey2.toString());
		 * 
		 * System.out.println("====私钥对比====");
		 * System.out.println(priKey.toString()); System.out.println("------");
		 * System.out.println(priKey2.toString());
		 */

		try {
			/*
			 * String pubKeyXml3 =
			 * "<RSAKeyValue><Modulus>rHESyuI3ny4MLsqDBalW9ySaodCL0e6Bsrl01Q5G1qm2wjUoGULazZSNqZY+JQNjU92tW3Snk5RPIkv+wDj+uOT9LTUjQImltHnzqMvbt06GipVXDOyBLTa7G/zRIe/CrjyJ+XEYX2xIhpe5ayowl3HHUpZ71jRNioyxaVVZ8S0=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"
			 * ; String priKeyXml3 =
			 * "<RSAKeyValue><Modulus>rHESyuI3ny4MLsqDBalW9ySaodCL0e6Bsrl01Q5G1qm2wjUoGULazZSNqZY+JQNjU92tW3Snk5RPIkv+wDj+uOT9LTUjQImltHnzqMvbt06GipVXDOyBLTa7G/zRIe/CrjyJ+XEYX2xIhpe5ayowl3HHUpZ71jRNioyxaVVZ8S0=</Modulus><Exponent>AQAB</Exponent><P>5a7uM+IeY8QMVQl0q88ZTqWbB555l7+366cUIClTN8z2ZXzTnWFCNoQzUrG14FouJFYumFZD12Ni5MkJK6gqSw==</P><Q>wDMhwwO4kz82uSG+FlCBr06fYk2COTg0TofmSp/5OrVqgkBIe7FgpTpVGzGLk0mvOLcy6UZftq//W0Saow6nZw==</Q><DP>FbjDgliiMyE5YVlxlUYSyKNU1BWivj09caXte1UtL5vMubBiewHVtz4tdGamIr+kmX8lDPcrl1Uo5yY0HdLbnQ==</DP><DQ>kIjjJsgxkWnEOUyKqjU4kSDK8x3ehDEkBLpmEFBlGCU9R14YJAyr5RUM0zpbABQ1VK1P9+UYLUYE/hmFQIHQmQ==</DQ><InverseQ>pxQDThwSnUZ4EaNaCPl1ovYypdQUZaZ/Sld1+0n8FEjkmRcGP1R9VMuj1ViPZg3rvm2GeP8Xv1SJqJUVueWiGA==</InverseQ><D>DxBNoPWEAF7IZ6n/KhZx52MGMw6BuFQKdm9m+lml7Iik03BLUXGapYzNlzvtr9QM8D2UMEIPhX/WLdvPpEEWVzGnD7XpLXjGwfu1ZkJRcXPEZEZ2subh5ZBqOWCFWKv5WwgGYWuYDLHfrBlBgSFWR8cZuyqkmMsWl4CiadXqGA0=</D></RSAKeyValue>"
			 * ;
			 * 
			 * System.out.println((new Date()).toLocaleString() + ": 加载公钥中。。。");
			 * PublicKey pubKey3 = RsaHelper.decodePublicKeyFromXml(pubKeyXml3);
			 * System.out.println((new Date()).toLocaleString() + ": 加载私钥中。。。");
			 * PrivateKey priKey3 =
			 * RsaHelper.decodePrivateKeyFromXml(priKeyXml3);
			 * 
			 * String dataStr =
			 * "Java与.NET和平共处万岁！sdfasdfasdfassssssssssssssssssssssdfasdfffdasdfasssssssssssssssssssssssssssssssssssss"
			 * ; System.out.println("加密前明文:" + dataStr + " , 它的长度:" +
			 * dataStr.length()); byte[] dataByteArray =
			 * dataStr.getBytes("utf-8");
			 * System.out.println("加密前明文data的Base64表示：" +
			 * Base64Helper.encode(dataByteArray));
			 * 
			 * System.out.println((new Date()).toLocaleString() + ": 加密中。。。");
			 * // 加密 byte[] encryptedDataByteArray = RsaHelper.encryptData(
			 * dataByteArray, pubKey3);
			 * 
			 * System.out.println("encryptedData的Base64表示(加密后用bease64表示:)：" +
			 * Base64Helper.encode(encryptedDataByteArray));
			 * System.out.println((new Date()).toLocaleString() + ": 解密中。。。");
			 * // 解密 // byte[] byte[] decryptedDataByteArray =
			 * RsaHelper.decryptData( encryptedDataByteArray, priKey3);
			 * System.out.println("解密后: " + new String(decryptedDataByteArray,
			 * "utf-8"));// 签名 System.out.println((new Date()).toLocaleString()
			 * + ": 签名中。。。"); byte[] signDataByteArray =
			 * RsaHelper.signData(dataByteArray, priKey3);
			 * System.out.println("signData的Base64表示：" +
			 * Base64Helper.encode(signDataByteArray)); // 验签
			 * System.out.println((new Date()).toLocaleString() + ": 验签中。。。");
			 * boolean isMatch = RsaHelper.verifySign(dataByteArray,
			 * signDataByteArray, pubKey3); System.out.println("验签结果：" +
			 * isMatch);
			 */

			/*
			 * String pubKeyXml3 = RsaHelper.encode64PublicKeyString(pubKey);
			 * String priKeyXml3 = RsaHelper.encode64PrivateKeyString(priKey);
			 * System.out.println("====公钥===="); System.out.println(pubKeyXml3);
			 * System.out.println("====私钥===="); System.out.println(priKeyXml3);
			 * 
			 * System.out.println((new Date()).toLocaleString() + ": 加载公钥中。。。");
			 * // PublicKey pubKey3 =
			 * RsaHelper.decodePublicKeyFromXml(pubKeyXml3); PublicKey pubKey3 =
			 * RsaHelper.decodePublicKeyFromBase64Str(pubKeyXml3);
			 * System.out.println((new Date()).toLocaleString() + ": 加载私钥中。。。");
			 * // PrivateKey priKey3 =
			 * RsaHelper.decodePrivateKeyFromXml(priKeyXml3); PrivateKey priKey3
			 * = RsaHelper.decodePrivateKeyFromBase64Str(priKeyXml3);
			 * 
			 * String dataStr = "Java与.NET和平共处万岁！sssssssssssssssssssssssss";
			 * System.out.println("加密前明文:" + dataStr + " , 它的长度:" +
			 * dataStr.length()); byte[] dataByteArray =
			 * dataStr.getBytes("utf-8");
			 * System.out.println("加密前明文data的Base64表示：" +
			 * Base64Helper.encode(dataByteArray));
			 * 
			 * System.out.println((new Date()).toLocaleString() + ": 加密中。。。");
			 * // 加密 byte[] encryptedDataByteArray = RsaHelper.encryptData(
			 * dataByteArray, pubKey3);
			 * 
			 * System.out.println("encryptedData的Base64表示(加密后用bease64表示:)：" +
			 * Base64Helper.encode(encryptedDataByteArray)); String
			 * encryptedData = Base64Helper.encode(encryptedDataByteArray);
			 * System.out.println((new Date()).toLocaleString() + ": 解密中。。。");
			 * // 解密 // byte[] byte[] decryptedDataByteArray =
			 * RsaHelper.decryptData( Base64Helper.decode(encryptedData),
			 * priKey3); System.out.println("解密后: " + new
			 * String(decryptedDataByteArray, "utf-8"));// 签名
			 */
			/*
			 * System.out.println((new Date()).toLocaleString() + ": 签名中。。。");
			 * byte[] signDataByteArray = RsaHelper.signData(dataByteArray,
			 * priKey3); System.out.println("signData的Base64表示：" +
			 * Base64Helper.encode(signDataByteArray)); // 验签
			 * System.out.println((new Date()).toLocaleString() + ": 验签中。。。");
			 * boolean isMatch = RsaHelper.verifySign(dataByteArray,
			 * signDataByteArray, pubKey3); System.out.println("验签结果：" +
			 * isMatch);
			 */

			Map<String, String> keysMap = RSAUtils.generateKeys();
			String publicKeyStr = keysMap.get(RSAUtils.PUBLIC_KEY);
			String privateKeyStr = keysMap.get(RSAUtils.PRIVATE_KEY);
			System.out.println("公钥为：" + publicKeyStr);
			System.out.println("私钥为：" + privateKeyStr);

			publicKeyStr = "<RSAKeyValue><Modulus>AKTtw0J9zIh819WHzFvtxiCTEM/sYbhD5/8m7FZUR7Kas3XD1lIpP50PchKLo+OEAx0AliwWDRMx9TZUK+cS7U2qT4ekDWYA2MNiw2ND0ehe+tXcyVA/KHa0BEl3LssfShaF8NPF9C1YY2l/bMO84LszXKpmOkUrJfFGJsIGbNfv</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
			privateKeyStr = "<RSAKeyValue><Modulus>AKTtw0J9zIh819WHzFvtxiCTEM/sYbhD5/8m7FZUR7Kas3XD1lIpP50PchKLo+OEAx0AliwWDRMx9TZUK+cS7U2qT4ekDWYA2MNiw2ND0ehe+tXcyVA/KHa0BEl3LssfShaF8NPF9C1YY2l/bMO84LszXKpmOkUrJfFGJsIGbNfv</Modulus><Exponent>AQAB</Exponent><P>AOhUizFjuK+6pQxfKC6fsPYyK3Ywli3gzcs254IMKnlBqHMEEBSD3O0SOzO87nrXqfX7o78x3Tu7s6Zq4ZZA2CU=</P><Q>ALW7TlT+mtI3kiz7aXT/Oa0Wnj/V1yjPyIRSN+0kwZ25wKEbZuDKObXNGPnfYzC3LaZQ0eeBcJ9/m5TLrGVGOYM=</Q><DP>AK5bxJqsXE6FpJhEUcOr1QLvY+6vSAXmUIvSCKxwtO+Ldv/abLb4vzSsGgIaKF/IuqUA1UMICSBrHcgnLmW1BIE=</DP><DQ>P7YrACFCpfBVju+VSS8xST1kvXx6shQmeD1a3gjE2EcHAXRZ3PUIxnPhDbkDTVDq8CPlcwQuN7zFDqVZCyhTgQ==</DQ><InverseQ>bMR1EoIA3n0TiTQ6DMX1cY90be/Y08XZgqWmHiyGppuJxoOcIlrU3RJXk+k8be3KjKMeg3ZTpWV8lAkA/2hO/Q==</InverseQ><D>B1DQl3NzDh7TiBI0+2LppepAFaj7kKvab5PvacjlQUPhb/jW2eAghTv5KF9vTpk9dhzfjGcR/2b45IcJR3+sbPIiJPwF6ZUdbtwrXRkJCf44YJebj2sWXiq2199w4GLC8qiYy9ApfdphWHy/jT+9bSX3Pw+70d6GntdzXiuZk5k=</D></RSAKeyValue>";

			String userName = "hope0love";
			String userNameEncryptedData = RSAUtils.encryptByPublicKey(userName, publicKeyStr);
			System.out.println("userName密文为：" + userNameEncryptedData);
			String userNameDecryptedData = RSAUtils.decryptByPrivateKey(userNameEncryptedData, privateKeyStr);
			System.out.println("userName解密后:" + userNameDecryptedData);

			String a = RSAUtils.encryptByPrivateKey(userName, privateKeyStr);
			System.out.println("userName密文(私钥加密)为：" + userNameEncryptedData);
			String b = RSAUtils.decryptByPublicKey(userNameEncryptedData, publicKeyStr);
			System.out.println("userName解密(公钥解密)后:" + userNameDecryptedData);

			String password = "25D55AD283AA400AF464C76D713C07AD";
			String passwordEncryptedData = RSAUtils.encryptByPublicKey(password, publicKeyStr);
			System.out.println("password密文为：" + passwordEncryptedData);
			String passwordDecryptedData = RSAUtils.decryptByPrivateKey(passwordEncryptedData, privateKeyStr);
			System.out.println("password解密后:" + passwordDecryptedData);

		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}
